package br.com.sovi.gwt.server.rest;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import br.com.sovi.gwt.server.service.CurrentToken;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;

public abstract class RestController {

	public static final String TOKEN_AUTH = "X-Token-Auth-Header";

	public static <T> T get(String url, GenericType<T> genericType) {
		Client client = Client.create();

		WebResource resource = client.resource(url);

		ClientResponse clientResponse = resource.type(MediaType.APPLICATION_JSON).header(TOKEN_AUTH,
				CurrentToken.getCurrent()).get(ClientResponse.class);

		return clientResponse.getEntity(genericType);
	}

	public static <T> T get(String url, MultivaluedMap<String, String> queryParams) {
		Client client = Client.create();

		WebResource resource = client.resource(url);

		ClientResponse clientResponse = resource.queryParams(queryParams).type(MediaType.APPLICATION_JSON).header(
				TOKEN_AUTH, CurrentToken.getCurrent()).get(ClientResponse.class);

		return clientResponse.getEntity(new GenericType<T>() {
		});
	}

	public static <T> T post(String url, GenericType<T> genericType, Object content) {
		Client client = Client.create();

		WebResource resource = client.resource(url);

		ClientResponse clientResponse = resource.type(MediaType.APPLICATION_JSON).header(TOKEN_AUTH,
				CurrentToken.getCurrent()).post(ClientResponse.class, content);

		return clientResponse.getEntity(genericType);
	}

}
